﻿#!/usr/bin/python3

#pip3 install xlrd==1.2.0
import xlrd
import time

import os
import sys
import string
import getopt

import json

import xml.etree.ElementTree as etree
from xml.etree.ElementTree import SubElement

default_json = '{"configurations":[{"intelliSenseMode":"clang-x64","name":"Win32","cppStandard":"c++11","cStandard":"c99","compilerPath":"","includePath":[],"defines":[]}]}'

inc_path = []


def main(argv):
    inputfile = ''
    outputfile = ''
    projectfile = ''
    try:
        opts, args = getopt.getopt(argv,"hi:o:p:",["ifile=","ofile=","project="])
    except getopt.GetoptError:
        print(' -i <inputfile> -o <outputfile> -p <project file>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(' -i <inputfile> -o <outputfile> -p <project file>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif opt in ("-p", "--project"):
            projectfile = arg
            
    print('输入的文件为：', inputfile)
    print('输出的文件为：', outputfile)
    print('项目文件：', projectfile)

    print("Hello, World! 123")
    template_tree = etree.parse(projectfile)
    filepath = os.path.dirname( os.path.abspath(projectfile) )
    print(filepath)
    
    print("Hello, World! 456")
    IncludePath = template_tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/IncludePath')
    mdk_incpath = IncludePath.text.split(';')
    print(str(mdk_incpath))
    
    Define = template_tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/Define')
    mdk_define = Define.text.split(',')
    print(str(mdk_define))

    print("Hello, World! 789")
    
    if os.path.exists(inputfile):
        json_in_file = open(inputfile, 'r')
        json_in_str = json_in_file.read()
        json_in_file.close()
    else :
        json_in_str = default_json
        json_in_file = open(inputfile, 'w')
        json_in_file.write( json.dumps(json.loads(json_in_str), indent=4 ) )
        json_in_file.close()

    json_in_obj = json.loads(json_in_str)
    
    #includePath 
    print(str(json_in_obj['configurations'][0]['includePath'] ))
    
    for item in mdk_incpath:
        inc_path = os.path.join(filepath, item)
        json_in_obj['configurations'][0]['includePath'].append(inc_path)
    
    print(str(json_in_obj['configurations'][0]['includePath'] ))
    
    #define
    print(str(json_in_obj['configurations'][0]['defines'] ))
    
    for item in mdk_define:
        json_in_obj['configurations'][0]['defines'].append(item)
        
    print(str(json_in_obj['configurations'][0]['defines'] ))
    
    json_out_str = json.dumps(json_in_obj, indent=4)
    
    
    json_out_file = open(outputfile, 'w')
    
    json_out_file.write(json_out_str)
    
    json_out_file.close()
    

if __name__ == "__main__":
   main(sys.argv[1:])
   
   
   